﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;

namespace webapiDemo.Filters
{
    /// <summary>
    /// 封装统一返回结果
    /// </summary>
    public class ApiResultAttribute : System.Web.Http.Filters.ActionFilterAttribute
    {
        public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
        {
            base.OnActionExecuted(actionExecutedContext);

            // 不需要封装统一返回结果
            if (actionExecutedContext.ActionContext.ActionDescriptor.GetCustomAttributes<NoApiResultAttribute>().Any()) {
                return;
            }


            //初始化返回结果
            ApiResult result = new ApiResult();
            if (actionExecutedContext.Exception != null)
            {
                result.message = "sys_error";
                result.success = false;
                result.data = actionExecutedContext.Exception.Message;
            }
            else
            {
                

                object resultObj = null;
                var a = actionExecutedContext.ActionContext.Response.Content.ReadAsAsync<object>();
                if (!a.IsFaulted)
                {
                    // 取得由 API 返回的资料
                    resultObj = actionExecutedContext.ActionContext.Response.Content.ReadAsAsync<object>().Result;
                }
                if (resultObj is ApiResult)
                {
                    result = resultObj as ApiResult;
                }
                else {
                    result.data = resultObj;
                    //请求是否成功
                    result.success = actionExecutedContext.ActionContext.Response.IsSuccessStatusCode;
                    // 取得由 API 返回的状态代码
                    result.code = actionExecutedContext.ActionContext.Response.StatusCode.ToString();
                }

                
            }


            //
            actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(actionExecutedContext.ActionContext.Response.StatusCode, result);

        }

    }
}